package com.csscaps.system.shiro.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Iterator;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.csscaps.system.constant.BaseConstant;
import com.csscaps.system.utils.ResultUtil;
import com.csscaps.system.utils.StringUtils;
import com.csscaps.system.utils.UUIDGenerator;

/**
 * @file AuthCheckFilter.java
 * @author AlexWang
 * @version 0.1
 * @desc 1：系统统一访问权限处理类 Copyright(C), 2017 cssscaps History 1. Date: 2017-05-22
 *       05:04:04 Author: alexwang Modification: this file was created 2. ...
 */

@Component
public class AuthCheckFilter implements Filter {

	private static final Logger log = LoggerFactory.getLogger(AuthCheckFilter.class);

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest hreq = (HttpServletRequest) req;
		log.info(hreq.getRequestURI());
		// 如果是API文件管理静态资源文件，则不做过滤验证
		if (checkUnInterception(hreq.getRequestURI())) {
			chain.doFilter(req, res);
		} else {
			String reqMethod = hreq.getMethod();
			// POST 请求key 验证
			if (BaseConstant.RequestModePost.equals(reqMethod)) {
				try {
					ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(hreq);
					String body = HttpHelper.getBodyString(requestWrapper);
					// 如果是POST请求则需要获取 param 参数
					String bodyStr = URLDecoder.decode(body, "utf-8");
					JSONObject bodyJSON = JSONObject.parseObject(bodyStr);
					// 如果授权码合法则放行，否则返回错误码
					Object userInfo = SecurityUtils.getSubject().getPrincipal();
					//1：用戶身份和系统授权待实现
					if (userInfo != null) {
						chain.doFilter(requestWrapper, res);

					} else {
						log.error("UncheckAuth url: " + hreq.getRequestURI());
						unauthorized(res);
					}
				} catch (Exception e) {
					log.error("checkAuth Exception: " + e.getMessage());
					log.error("UncheckAuth url: " + hreq.getRequestURI());
					unauthorized(res);
				}
			} else {

				try {

					Object userInfo = SecurityUtils.getSubject().getPrincipal();
					if (userInfo != null) {
						// 如果授权码合法则放行，否则返回错误码

						chain.doFilter(req, res);
					} else {
						log.error("UncheckAuth url: " + hreq.getRequestURI());
						unauthorized(res);
					}
				} catch (Exception e) {
					log.error("checkAuth Exception: " + e.getMessage());
					log.error("UncheckAuth url: " + hreq.getRequestURI());
					unauthorized(res);
				}

			}
		}

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

	public void unauthorized(ServletResponse res) throws IOException {

		HttpServletResponse response = (HttpServletResponse) res;
		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(JSON.toJSONString(ResultUtil.getNoAuthorityResult()));
		out.flush();
	}

	private boolean checkAuth(String key) throws Exception {

		if (StringUtils.isEmpty(key)) {

			return false;
		}
		boolean isHasAuthority = false;
		/*
		 * String md5Key = MD5Encrypter.md5Encrypt(key, MD5Encrypter.iotBaseSalt); if
		 * (authService.exists(md5Key)) { isHasAuthority = true; }
		 */
		return isHasAuthority;
	}

	private boolean checkUnInterception(String url) {
		/*
		 * APIManager apiManager = ConfigService.getAPIManagerConfig(); if(apiManager ==
		 * null || (!apiManager.isShowAPI())){ return false; }
		 * if(StringUtils.isEmpty(url)) { return false; }
		 */
		Iterator unInterceptionIterator = BaseConstant.unInterceptionSet.iterator();// 先迭代出来
		boolean contains = false;
		while (unInterceptionIterator.hasNext()) {// 遍历
			if (url.contains(String.valueOf(unInterceptionIterator.next()))) {
				contains = true;
				break;
			}
		}
		return contains;
	}

}